<?php
require_once dirname(__FILE__) . '/../lib/Forage.php';
require_once 'Console/Getopt.php';

$short = 'vi:a:d:l:f:h';
$long  = array('verbose', 'index=', 'sortasc=', 'sortdesc=', 'limit=', 'fields=', 'help');

function showHelp()
{
  $help = <<<END_TEXT
NAME
  searcher - Search an index through Forage

SYNOPSIS
  php searcher.php [options] [query]

DESCRIPTION
  The parser utility of the wikipedia package parses Wikipedia dump
  files and indexes them through Forage in a supported backend.

OPTIONS
  -v, --verbose
    Print verbose logging messages
  -i DSN, --index=DSN
    The DSN used to load a Forage object to index the documents with
  -a field, --sortasc=field
  -d field, --sortdesc=field
  -l LIMIT, --limit=LIMIT
    Limit the result set to LIMIT number of documents
  -h, --help
    Show this help

EXAMPLE
  php searcher.php --verbose --index='solr:127.0.0.1:8080' pasta

END_TEXT;
  echo $help;
}

$con  = new Console_Getopt();
$args = $con->readPHPArgv();
array_shift($args);
$options = $con->getopt2($args, $short, $long);
$verbose = false;
$dsn     = null;
$sort    = null;
$fields  = array('title');
$limit   = 20;
$query   = '';

if ($options instanceof PEAR_Error) {
  echo "Pear Error: " . $options->getMessage() . "\n";
  die();
}

foreach ($options[0] as $option) {
  switch ($option[0]) {
  case '--verbose':
  case 'v':
    $verbose = true;
    break;
  case '--index':
  case 'i':
    $dsn = $option[1];
    break;
  case '--sortasc':
  case 'a':
    $sort = array($option[1], SORT_ASC);
    break;
  case '--sortdesc':
  case 'd':
    $sort = array($option[1], SORT_DESC);
    break;
  case '--limit':
  case 'l':
    $limit = $option[1];
    break;
  case '--fields':
    $fields = explode(',', $option[1]);
    break;
  case '--help':
  case 'h':
  default:
    showHelp();
    die();
    break;
  }
}

$query = implode(' ', $options[1]);

if (!$dsn) {
  echo "ERROR: No index DSN set\n";
  die();
}

$forage = Forage::create($dsn);
$query  = $forage->getQuery($query);
$query->setPerPage($limit);
if ($sort) {
  $query->addSortField($sort[0], $sort[1]);
}
$result = $forage->search($query);
echo "Found " . $result->total . " documents\n";
foreach ($result as $document) {
  $first = true;
  foreach ($fields as $field) {
    echo (!$first?' - ':'') . $document[$field];
    $first = false;
  }
  echo " (" . $document->getProperty('score') . ")\n";
}
